package com.googlecode.cswish.struts.conversion;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.util.StrutsTypeConverter;

import com.googlecode.cswish.Config;
import com.opensymphony.xwork2.XWorkException;
import com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter;
import com.opensymphony.xwork2.inject.Inject;

/**
 * A helper class, it uses the date format configured in <s:date> to
 *  convert the date type
 * <p>
 * You can add the following configuration to "xwork-conversion.properties":
 * java.util.Date=com.googlecode.cswish.struts.conversion.DefaultDateConverter
 * 
 * @author Jerry.Feng 2008-12-1
 */
public class DefaultDateConverter extends StrutsTypeConverter {

	private static final Logger logger = Logger.getLogger(DefaultDateConverter.class);
	
	@Inject
	private XWorkBasicConverter xworkBasicConverter;
	
	@Resource
	private Config config;
	
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		Date date = null;  
		String sDate = null;  
		if (values != null && values.length > 0) {
			sDate = values[0];  
			if (sDate != null && sDate.length() > 0) {
				// Read date format
				String format = config.getDataFormat();
				if (format != null) {
					try {
						// Convert it
						date = new SimpleDateFormat(format).parse(sDate);
					} catch (ParseException e) {
		                throw new XWorkException("Could not parse date", e);
		            }
				} else {
					date = (Date) xworkBasicConverter.convertValue(context, values, toClass);
				}
			}
		}
		return date;
	}

	@Override
	public String convertToString(Map context, Object o) {
		return convertToString(context, o, false);
	}
	
	public String convertToString(Map context, Object o, boolean isDetailDate) {
		Date date = (Date) o;
		String sDate = null;
		if (o != null) {
			// Read date format 
			String format;
			if (isDetailDate) {
				format = config.getDetailDataFormat();
			} else {
				format = config.getDataFormat();
			}
			// Convert it
			if (format != null) {
				try {
					sDate = new SimpleDateFormat(format).format(date);
				} catch (Exception ex) {
					logger.error("Wrong data format:" + format, ex);
				}
			}
			if (sDate == null) {
				sDate = (String) xworkBasicConverter.convertValue(context, o, String.class);
			}
		}
		return sDate;
	}
}